/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openFuyao is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

// Package logger 负责记录执行过程中的日志
package logger

import (
	"fmt"
	"os"
	"sync"
	"time"

	"env-check/pkg/config"
)

// LogLevel 日志级别类型
type LogLevel int

const (
	// LevelInfo 信息
	LevelInfo LogLevel = iota
	// LevelSuccess 成功
	LevelSuccess
	// LevelWarning 警告
	LevelWarning
	// LevelError 报错
	LevelError
)

// Logger 日志器
type Logger struct {
	logFile string
	mu      sync.Mutex
}

// NewLogger 创建新的日志器
func NewLogger(logFile string) *Logger {
	return &Logger{
		logFile: logFile,
	}
}

// Log 记录日志
func (l *Logger) Log(level LogLevel, message string) {
	timestamp := time.Now().Format("2006-01-02 15:04:05")

	var levelStr string
	switch level {
	case LevelInfo:
		levelStr = "INFO"
	case LevelSuccess:
		levelStr = "SUCCESS"
	case LevelWarning:
		levelStr = "WARNING"
	case LevelError:
		levelStr = "ERROR"
	default:
		levelStr = "INFO"
	}

	logEntry := fmt.Sprintf("[%s][%s] %s", levelStr, timestamp, message)

	// 输出到控制台（带颜色）
	l.printColored(level, logEntry)

	// 写入日志文件
	l.writeToFile(logEntry)
}

// 带颜色输出到控制台
func (l *Logger) printColored(level LogLevel, message string) {
	l.mu.Lock()
	defer l.mu.Unlock()

	switch level {
	case LevelInfo:
		fmt.Printf("\033[34m%s\033[0m\n", message) // 蓝色
	case LevelSuccess:
		fmt.Printf("\033[32m%s\033[0m\n", message) // 绿色
	case LevelWarning:
		fmt.Printf("\033[33m%s\033[0m\n", message) // 黄色
	case LevelError:
		fmt.Printf("\033[31m%s\033[0m\n", message) // 红色
	default:
		fmt.Printf("\033[34m%s\033[0m\n", message) // 蓝色
	}
}

// 写入日志文件
func (l *Logger) writeToFile(message string) {
	if l.logFile == "" {
		return
	}

	l.mu.Lock()
	defer l.mu.Unlock()

	file, err := os.OpenFile(l.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, config.FileMode)
	if err != nil {
		fmt.Printf("open log file failed: %v\n", err)
		return
	}
	defer file.Close()

	_, err = file.WriteString(message + "\n")
	if err != nil {
		fmt.Printf("write to log file failed: %v\n", err)
	}
}

// Info 记录信息
func (l *Logger) Info(message string) {
	l.Log(LevelInfo, message)
}

// Success 记录成功操作
func (l *Logger) Success(message string) {
	l.Log(LevelSuccess, message)
}

// Warning 记录警告信息
func (l *Logger) Warning(message string) {
	l.Log(LevelWarning, message)
}

// Error 记录报错
func (l *Logger) Error(message string) {
	l.Log(LevelError, message)
}
